<template>
    <div class="forget">
        <div class="forget_top" style="cursor: default">
            <span>全渠道自动化 营销运营平台</span>
            <span>构建私域流量，打破营销困局</span>
        </div>
        <div class="forgetForm">
            <span class="title" style="cursor: default">忘记密码</span>
            <el-form
                ref="ruleFormRef"
                :model="numberValidateForm"
                label-width="90px"
                class="demo-ruleForm"
                :rules="rules"
                label-position="left">
                <el-form-item prop="phone" label="手机号码">
                    <el-input
                        v-model.number="numberValidateForm.phone"
                        class="input"
                        type="text"
                        placeholder="请填写要找回的手机号码"
                        autocomplete="off"
                        max-length="11">
                    </el-input>
                </el-form-item>
                <el-form-item prop="imgCode" label="图片验证码">
                    <el-input
                        v-model="numberValidateForm.imgCode"
                        class="input"
                        type="text"
                        placeholder="请填写图片验证码"
                        max-length="4">
                        <template #suffix>
                            <div class="imgCode" style="cursor: pointer" @click="randomCode">
                                <img :src="getImgCode" alt="" />
                            </div>
                        </template>
                    </el-input>
                </el-form-item>
                <el-form-item prop="verificationCode" label="短信验证码">
                    <el-input
                        v-model.number="numberValidateForm.verificationCode"
                        class="input"
                        type="text"
                        placeholder="请填写短信验证码"
                        max-length="6">
                        <template #suffix>
                            <div
                                v-show="sendAuthCode"
                                class="getCode"
                                style="color: #0081ff; cursor: pointer"
                                @click="getPhoneCode(ruleFormRef)">
                                获取验证码
                            </div>
                            <div v-show="!sendAuthCode" class="getCode countDown">{{ autoTime }}后重新获取</div>
                        </template>
                    </el-input>
                </el-form-item>
                <el-form-item prop="newPassword" label="新密码">
                    <el-input
                        v-model="numberValidateForm.newPassword"
                        class="input"
                        type="password"
                        placeholder="请填写包含字母数字的6-20位密码"
                        min-length="6"
                        autocomplete="new-password"
                        max-length="20">
                    </el-input>
                </el-form-item>
                <el-form-item prop="sureNewPassword" label="确认新密码">
                    <el-input
                        v-model="numberValidateForm.sureNewPassword"
                        class="input"
                        type="password"
                        placeholder="请再次输入新密码"
                        min-length="6"
                        max-length="20">
                    </el-input>
                </el-form-item>
                <el-from-item>
                    <el-button style="margin-top: 15px" @click="Retrieve(ruleFormRef)">提交更新</el-button>
                </el-from-item>
            </el-form>
        </div>
        <div v-if="move" class="move">
            <div class="account">
                <div class="top">请选择您要找回的账号</div>
                <div class="center">
                    <card
                        v-for="(item, index) in data"
                        :key="index"
                        :card-data="item"
                        style="cursor: pointer"
                        @click="check(index)"></card>
                </div>
                <div class="bottom">
                    <div>
                        您将同时更新已选的&nbsp;
                        <span style="color: orange; font-size: 20px">{{ count }}</span>
                        &nbsp;个账号的密码
                    </div>
                    <div class="btn">
                        <el-button size="small" @click="move = false">取消</el-button>
                        <el-button size="small" @click="checkAll(count)">
                            {{ count === data.length ? '取消全选' : '全选' }}
                        </el-button>
                        <el-button size="small" @click="goLogin">确认找回</el-button>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { ElForm, ElMessage } from 'element-plus';
import { validatorPassword, validatePhone, validateCode, validatorNote } from '@/utils/validate';
import { noteCode } from '@/api/login';
import { forgetPassword, accountPassword } from '@/api/forget';
import { getImageCode } from '@/api/common';
import router from '@/router';

// 组件
import card from './components/card.vue';

// 表单数据
const numberValidateForm = reactive({
    phone: '',
    imgCode: '',
    verificationCode: '',
    newPassword: '',
    sureNewPassword: ''
});
const autoTime = ref(0);
const ruleFormRef = ref<InstanceType<typeof ElForm>>();

const count = ref(1);
const move = ref(false);
const sendAuthCode = ref(true);
const getImgCode = ref('');
const data = reactive([]);
// 手机号验证
const phone = (rule: any, value: any, callback: any) => {
    if (value == '') callback(new Error('手机号不能为空！'));
    else if (validatePhone(value)) {
        callback(new Error('手机格式有误！'));
    } else {
        callback();
    }
};
// 图片验证码验证
const imgCode = (rule: any, value: any, callback: any) => {
    if (value == '') callback(new Error('验证码不能为空！'));
    else if (validateCode(value)) {
        callback(new Error('验证码格式错误！'));
    } else {
        callback();
    }
};
// 短信验证
const verificationCode = (rule: any, value: any, callback: any) => {
    if (value == '') callback(new Error('验证码不能为空！'));
    else if (validatorNote(value)) {
        callback(new Error('验证码格式错误！'));
    } else {
        callback();
    }
};
// 密码验证
const newPassword = (rule: any, value: any, callback: any) => {
    if (value == '') {
        callback(new Error('密码不能为空！'));
    } else if (validatorPassword(value)) {
        callback(new Error('密码格式有误！'));
    } else callback();
};
// 确认密码
const sureNewPassword = (rule: any, value: any, callback: any) => {
    if (value == '') {
        callback(new Error('密码不能为空！'));
    } else if (value !== numberValidateForm.newPassword) {
        callback(new Error('两次密码输入不一致！'));
    } else callback();
};

// 校验规则
const rules = reactive({
    phone: [{ validator: phone, trigger: 'change' }],
    imgCode: [{ validator: imgCode, trigger: 'change' }],
    verificationCode: [{ validator: verificationCode, trigger: 'change' }],
    newPassword: [{ validator: newPassword, trigger: 'change' }],
    sureNewPassword: [{ validator: sureNewPassword, trigger: 'change' }]
});

// 点击时更换图片
const randomCode = async () => {
    const res: any = await getImageCode({ captcha_type: 'forget_password' });
    getImgCode.value = `data:image/png;base64,${res.base64_image}`;
};

// 获取短信验证码
const getPhoneCode = (formEl: any) => {
    if (numberValidateForm.phone != '' && numberValidateForm.imgCode != '') {
        const { phone, imgCode } = numberValidateForm;
        const params = {
            mobile: phone + '',
            image_verify_code: imgCode,
            sms_type: 'forget_password'
        };
        noteCode(params)
            .then((data: any) => {
                sendAuthCode.value = false;
                autoTime.value = 60;
                const autoTimeTimer = setInterval(() => {
                    autoTime.value--;
                    if (autoTime.value <= 0) {
                        sendAuthCode.value = true;
                        clearInterval(autoTimeTimer);
                    }
                }, 1000);
            })
            .catch((err: any) => {
                if (err.code == 10001) {
                    ElMessage.error(err.msg);
                    randomCode();
                }
            });
    } else {
        ElMessage.error('请填写手机号或图片验证码');
    }
};

// 选择账号
const check = (index: number) => {
    let num = 0;

    data.forEach((v, i) => {
        v.check = false;
        if (i === index) {
            v.check = true;
        }

        if (v.check) {
            num++;
        }
    });

    count.value = num;
};

// 选择全部账号
const checkAll = (num: number) => {
    if (num === data.length) {
        data.forEach((v, i) => {
            v.check = false;
        });
        data[0].check = true;
        count.value = 1;
    } else {
        data.forEach(v => {
            v.check = true;
        });
        count.value = data.length;
    }
};

// 找回成功
const goLogin = () => {
    const arr = [];
    data.forEach(v => {
        if (v.check) {
            arr.push(v.user_id);
        }
    });

    const { phone, newPassword, verificationCode } = numberValidateForm;
    const params = {
        mobile: `${phone}`,
        password: newPassword,
        user_ids: arr,
        sms_code: `${verificationCode}`
    };

    accountPassword(params).then(() => {
        router.push({ path: '/login' });
    });
};

// 找回密码
const Retrieve = (forgetEl: any) => {
    data.splice(0, data.length);
    if (!forgetEl) return;
    forgetEl.validate(valid => {
        if (valid) {
            const { phone, verificationCode, newPassword, sureNewPassword } = numberValidateForm;
            const params = {
                mobile: phone + '',
                password: newPassword,
                password_confirmation: sureNewPassword,
                sms_code: `${verificationCode}`
            };
            forgetPassword(params).then(res => {
                router.push({ path: '/login' });
                ElMessage.success('密码修改成功');
                data.push(...res.account_list);
                data.forEach((v, i) => {
                    v.check = true;
                    if (i > 0) {
                        v.check = false;
                    }
                });
                move.value = true;
            });
        } else {
            return false;
        }
    });
};

const GetForget = () => {
    numberValidateForm.phone = router.currentRoute.value.query.phone;
};
GetForget();
onMounted(() => {
    randomCode();
});
</script>

<style lang="scss" scoped>
.forget {
    margin: 0;
    padding: 0;
    display: flex;
    flex-direction: column;
    width: 100%;
    height: 100%;
    align-items: center;
    .forget_top {
        width: 100%;
        height: 200px;
        background: url('@/assets/login/register1_bg.png') no-repeat;
        background-size: 100% 100%;
        color: white;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        span:nth-child(1) {
            display: inline-block;
            font-size: 30px;
            margin-bottom: 10px;
        }
    }
    .forgetForm {
        display: flex;
        flex-direction: column;
        width: 500px;
        margin: 0;
        padding: 0;
        .title {
            display: inline-block;
            height: 60px;
            line-height: 60px;
            font-weight: bold;
        }
        .el-form-item {
            border-bottom: 1px solid #ccc;
            .input {
                :deep(.el-input__inner) {
                    padding: 0;
                    border: none;
                }
                :deep(.el-input__icon.el-icon) {
                    display: none;
                }
            }
            .imgCode {
                img {
                    width: 70px;
                }
            }
        }
        .el-button {
            width: 100%;
            background: rgba(255, 107, 0, 1);
            color: white;
            border: none;
        }
    }
    .move {
        position: fixed;
        width: 100%;
        height: 100%;
        background: rgba(144, 144, 144, 0.5);
        .account {
            width: 1000px;
            height: 600px;
            background: white;
            position: relative;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            display: flex;
            flex-direction: column;
            .top {
                width: 100%;
                height: 50px;
                line-height: 50px;
                padding-left: 20px;
                border-bottom: 1px solid #eee;
                font-weight: bold;
                box-sizing: border-box;
            }
            .center {
                flex: 1;
                display: flex;
                flex-direction: row;
                padding: 20px 0;
                box-sizing: border-box;
            }
            .bottom {
                width: 100%;
                height: 50px;
                line-height: 50px;
                padding: 0px 10px 0px 20px;
                border-top: 1px solid #eee;
                display: flex;
                flex-direction: row;
                justify-content: space-between;
                box-sizing: border-box;
                .btn {
                    .el-button:nth-child(1) {
                        border: 1px solid #ccc;
                        color: black;
                    }
                    .el-button:nth-child(2) {
                        border: 1px solid orange;
                        color: orange;
                    }
                    .el-button:nth-child(3) {
                        background: orange;
                        border: 1px solid orange;
                        color: white;
                    }
                }
            }
        }
    }
}
</style>
